package com.example.port.service.impl;

import com.example.port.entity.FeeRule;
import com.example.port.mapper.FeeRuleMapper;
import com.example.port.service.FeeRuleService;
import com.example.port.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class FeeRuleServiceImpl implements FeeRuleService {
    
    private static final Logger logger = LoggerFactory.getLogger(FeeRuleServiceImpl.class);
    
    private final FeeRuleMapper feeRuleMapper;
    
    @Autowired
    public FeeRuleServiceImpl(FeeRuleMapper feeRuleMapper) {
        this.feeRuleMapper = feeRuleMapper;
    }
    
    @Override
    public int insertFeeRule(FeeRule rule) {
        // 检查是否已设置ID，如果没有，则自动生成ID
        if (rule.getRuleId() == null) {
            Integer maxId = feeRuleMapper.getMaxRuleId();
            rule.setRuleId(maxId + 1);
        }
        return feeRuleMapper.insert(rule);
    }
    
    @Override
    public List<FeeRule> getAllFeeRules() {
        return feeRuleMapper.selectAll();
    }
    
    @Override
    @Transactional
    public int deleteFeeRule(Integer ruleId) {
        // 检查规则是否正在使用
        logger.info("检查费用规则ID: {} 是否被使用", ruleId);
        int count = feeRuleMapper.countStorageFeesByRuleId(ruleId);
        logger.info("费用规则ID: {} 关联的仓储费用记录数: {}", ruleId, count);
        
        if (count > 0) {
            logger.warn("费用规则ID: {} 已被仓储费用使用，无法删除", ruleId);
            throw new ServiceException("该费用规则已被仓储费用使用，无法删除");
        }
        
        logger.info("费用规则ID: {} 未被使用，可以删除", ruleId);
        return feeRuleMapper.delete(ruleId);
    }
    
    @Override
    public int updateFeeRule(FeeRule rule) {
        return feeRuleMapper.update(rule);
    }
    
    @Override
    public boolean isRuleInUse(Integer ruleId) {
        int count = feeRuleMapper.countStorageFeesByRuleId(ruleId);
        logger.info("费用规则ID: {} 关联的仓储费用记录数: {}", ruleId, count);
        return count > 0;
    }
} 
